<template>
  <el-dialog :visible="childVisible"
             title="选择运单"
             :before-close="close"
             width="80%"
             top="5vh"
             :close-on-click-modal="false"
             append-to-body>
    <el-form ref="form"
             :model="form"
             label-width="90px">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="合同编号">
            <!-- <InputMultiple v-model="form.contractNos"
                           placeholder="请输入合同编号" /> -->
            <dn-input-multiple v-model="form.contractNos"
                               placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="运输方式">
            <Select v-model="form.shipMode"
                    :options="shipModeOptions"
                    :placeholder="'请选择运输方式'" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="运输模式">
            <Select v-model="form.transportMode"
                    :options="transportModeOptions"
                    :placeholder="'请选择运输模式'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货时间">
            <el-date-picker v-model="form.fromTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="changeTime" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="5">
          <el-form-item label="运单状态">
            <Select v-model="form.waybillStatus"
                    :options="waybillStatusOptions"
                    :placeholder="'请选择运单状态'" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="发货省市区">
            <!-- <area-select align="center"
                         type="code"
                         check-strictly
                         :area-values="[
                form.fromAddress.provinceCode,
                form.fromAddress.cityCode,
                form.fromAddress.districtCode
              ]"
                         @input="selectFromArea" /> -->
            <area-cascader v-model="form.fromAddress"
                           :props="props"
                           :placeholder="`请选择省市区`" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="收货省市区">
            <!-- <area-select align="center"
                         type="code"
                         check-strictly
                         :area-values="[
                form.toAddress.provinceCode,
                form.toAddress.cityCode,
                form.toAddress.districtCode
              ]"
                         @input="selectToArea" /> -->
            <area-cascader v-model="form.toAddress"
                           :props="props"
                           :placeholder="`请选择省市区`" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="合单号">
            <el-input v-model="form.combineContractNo"
                      placeholder="请输入合单号"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="5">
          <el-form-item label="自营司机">
            <el-input v-model="form.contractNo"
                      placeholder="请输入自营司机"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="4">
          <el-button type="primary"
                     @click="handleQuery(1)">查询</el-button>
          <el-button type="primary"
                     @click="clean">清空</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer"
         class="dialog-footer">
      <el-pagination :current-page="page"
                     :page-size="pageSize"
                     :total="total"
                     :page-sizes="[10, 50, 100, 500, 1000]"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
      <div class="mt10">
        <el-button type="default"
                   @click="close">取消</el-button>
        <el-button type="primary"
                   @click="container">确定</el-button>
      </div>
    </div>
    <div>
      <account-list ref="accountList"
                    dialog-flag
                    :total-data="totalData"
                    :current-data="currentData"
                    :col-width="183"
                    :table-footer="false"
                    :selection-flag="true"
                    :operation-flag="false"
                    :create-type="createType" />
    </div>
  </el-dialog>
</template>

<script>
import AreaCascader from "@basic/area/AreaCascader.vue";
import AccountList from "./AccountList.vue";
import { finance } from "@/api/index";
import { pageTotal, billCache } from "./financeMap";
import Select from "@/components/advance/Select";
import { waybillStatusOptions, transportModeOptions, shipModeOptions } from "@/libs/constant.js"
export default {
  name: "AddAccountListDialog",
  components: { AreaCascader, AccountList, Select },
  props: {
    childVisible: Boolean,
    indexList: {
      type: Array,
      default: () => []
    },
    createType: {
      type: Number,
      default: () => null
    },
    customerId: {
      type: [String, Number],
      default: () => null
    },
    carrierId: {
      type: Number,
      default: () => null
    },
    driverId: {
      type: Number,
      default: null
    }
  },
  data () {
    return {
      form: {
        contractNos: [],
        fromTime: null,
        fromTimeBegin: null,
        fromTimeEnd: null,
        shipMode: null,
        transportMode: null,
        fromAddress: {
          city: null,
          cityCode: null,
          district: null,
          districtCode: null,
          province: null,
          provinceCode: null
        },
        toAddress: {
          city: null,
          cityCode: null,
          district: null,
          districtCode: null,
          province: null,
          provinceCode: null
        },
        consigneeName: null,
        combineContractNo: null,
        waybillStatus: null
      },
      props: {
        label: 'name',
        value: 'areaCode',
        checkStrictly: true
      },
      waybillStatusOptions,
      transportModeOptions,
      shipModeOptions,
      currentData: [], // 数据源
      totalData: [], //合计数据源
      page: 1,
      pageSize: 10,
      total: 0,
      billCache: {} // 全部合计数据
    };
  },
  created () {
    let params = {
      page: this.page,
      size: this.pageSize,
      sort: [
        {
          asc: false,
          name: "fromTime"
        }
      ],
      financeStatus: 0
    };
    if (this.createType === 1) {
      params.waybillType = [10];
      params.customerId = this.customerId;
    } else {
      params.waybillType = [20];
      params.carrierId = this.carrierId;
      params.driverId = this.driverId;
    }
    this.getListTotal(params);
  },
  methods: {
    // 列表查询
    async getList (params) {
      const { data } = await finance.search({ ...params });
      this.total = data?.page.total;
      this.currentData = data?.page.records;
      this.totalData = this.addTableFooter(
        data.pageTotal || {},
        this.billCache || {}
      );
    },
    // 全部总计
    async getListTotal (params) {
      // eslint-disable-next-line
      const { driverId, ...parameters } = params
      const { data } = await finance.getListTotal({ ...params });
      this.billCache = data;
      this.getList(params);
    },
    // 合计表数据源
    addTableFooter (page, total) {
      return [
        {
          contractNo: '本页小计',
          ...pageTotal,
          ...page
        },
        {
          contractNo: "全部合计",
          ...billCache,
          ...total
        }
      ];
    },
    // 时间
    changeTime () {
      console.log("this.form.fromTime", this.form.fromTime)
      if (this.form.fromTime) {
        this.form.fromTimeBegin = this.$moment(this.form.fromTime[0]).format(
          "YYYY-MM-DD 00:00:00"
        );
        this.form.fromTimeEnd = this.$moment(this.form.fromTime[1]).format(
          "YYYY-MM-DD 23:59:59"
        );
      } else {
        this.form.fromTimeBegin = null;
        this.form.fromTimeEnd = null;
      }
    },
    // 查询
    handleQuery (page) {
      this.page = page;
      let params = {
        page,
        size: this.pageSize,
        sort: [
          {
            asc: false,
            name: "fromTime"
          }
        ],
        financeStatus: 0
      };
      if (this.createType === 1) {
        params.waybillType = [10];
        params.customerId = this.customerId;
      } else {
        params.waybillType = [20];
        params.carrierId = this.carrierId;
        params.driverId = this.driverId;
      }

      for (let key in this.form) {
        if (this.form[key] && key != "fromAddress" && key != "toAddress")
          params[key] = this.form[key];
        if (key === "fromAddress" && this.form?.fromAddress?.provinceCode) {
          // k首字母转大写 + 从k索引1的位置提取字符，如 address => Address
          for (let k in this.form.fromAddress) {
            let toUpper = k[0].toUpperCase() + k.substr(1);
            let newKey = `from${toUpper}`;
            params[newKey] = this.form[key][k];
          }
        }
        if (key === "toAddress" && this.form?.toAddress?.provinceCode) {
          for (let k in this.form.toAddress) {
            let toUpper = k[0].toUpperCase() + k.substr(1);
            let newKey = `to${toUpper}`;
            params[newKey] = this.form[key][k];
          }
        }
      }
      this.getListTotal(params);
    },
    // 分页数量改变
    handleSizeChange (value) {
      this.pageSize = value;
      this.handleQuery(this.page);
    },
    // 当前页数改变
    handleCurrentChange (value) {
      this.page = value;
      this.handleQuery(value);
    },
    // 取消
    close () {
      this.$emit("update:childVisible", false);
    },
    // 清空
    clean () {
      this.form = {
        contractNos: [],
        fromTime: null,
        fromTimeBegin: null,
        fromTimeEnd: null,
        shipMode: null,
        transportMode: null,
        fromAddress: {
          city: "",
          cityCode: "",
          district: "",
          districtCode: "",
          province: "",
          provinceCode: ""
        },
        toAddress: {
          city: "",
          cityCode: "",
          district: "",
          districtCode: "",
          province: "",
          provinceCode: ""
        },
        consigneeName: null,
        combineContractNo: null,
        waybillStatus: null
      };

      let params = {
        page: this.page,
        size: this.pageSize,
        sort: [
          {
            asc: false,
            name: "fromTime"
          }
        ],
        financeStatus: 0
      };
      if (this.createType === 1) {
        params.waybillType = [10];
        params.customerId = this.customerId;
      } else {
        params.waybillType = [20];
        params.carrierId = this.carrierId;
        params.driverId = this.driverId;
      }
      this.getListTotal(params);
    },
    // 确定
    container () {
      if (
        this.$refs.accountList.selectData &&
        this.$refs.accountList.selectData.length > 0
      ) {
        let waybillIds = this.indexList.map((item) => {
          return item.waybillId;
        });
        let data = [];
        console.log("waybillIds", waybillIds);
        this.$refs.accountList.selectData.map((ele) => {
          if (!waybillIds.includes(ele.waybillId)) {
            data.push(ele);
          }
        });
        this.$emit("changeTableData", data);
        this.close();
      } else {
        this.$message.error("请勾选运单");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.mt10 {
  margin-top: 10px;
}
</style>
